package main.chapter4

import kotlin.text.StringBuilder

fun main(args: Array<String>) {
    val list = listOf(1, 3, 4, 5, 10, 8, 2)
    //高级函数map
    val newList = list.map {
        it * 2 + 3
    }
    newList.forEach(::println)

    val newList2 = list.map(Int::toDouble)
    newList2.forEach(::println)
    val newList22 = list.map {
        it.toDouble()
    }
    newList22.forEach(::println)

    val list1 = listOf(
        1..20,
        2..5,
        100..150
    )

    //flatMap高级函数，lambda表达式写出it更加清晰
    val flatList = list1.flatMap { intRange ->
        intRange.map { element ->
            "No.$element"
        }
    }

    flatList.forEach(::println)

    val flatList1 = list1.flatMap { it }
    //求和
    val sum = flatList1.reduce { acc, i -> acc + i }
    println(sum)

    (0..6).map(::factorial).forEach(::println)

    (0..7).map(::factorial).fold(5) { acc, i -> acc + i }

    (0..7).map(::factorial).fold(StringBuilder()) { acc, i -> acc.append(i).append(",") }.forEach(::print)

    //连接字符串
    (0..100).joinToString(",")

    //过滤奇数
    (0..20).filter { (it % 2 == 1) }.forEach(::println)
    //奇数下标的数
    (0..20).filterIndexed { index, i -> index % 2 == 1 }

    //取前10个遇到第一个不符合条件的结束
    (0..20).takeWhile { it < 10 }.forEach(::println)
}

fun factorial(n: Int): Int {
    if (n == 0) return 1
    return (1..n).reduce { acc, i -> acc * i }
}